package com.zking.web;

import com.zking.dao.domain.*;
import com.zking.service.ResourcesService;
import com.zking.service.SysRoleService;
import com.zking.service.UserService;
import com.zking.utils.RequestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.*;

@Controller
@RequiresPermissions("power")
@RequestMapping(value="/power",name = "后台权限管理器")
public class PowerController {
    @Autowired
    private UserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private ResourcesService resourcesService;

    @RequiresPermissions("power:toPowerIndex")
    @RequestMapping(value = "/toPowerIndex",name ="查看所有后台用户")
    public String toPowerIndex(HttpServletRequest request){
        String username = "未登录";
        SysUser currentLoginUser = RequestUtils.currentLoginUser();

        if (currentLoginUser != null && StringUtils.isNotEmpty(currentLoginUser.getUserName())) {
            username = currentLoginUser.getUserName();
        } else {
            return "redirect:/adminLogin/toLogin";
        }
        //查询所有用户
        List<SysUser> users = userService.findUsers();
        //查询每个用户对应的所有角色
        Map<SysUser, List<SysRole>> map = new TreeMap<SysUser, List<SysRole>>(
                new Comparator<SysUser>() {
                    @Override
                    public int compare(SysUser o1, SysUser o2) {
                        return o1.getId().compareTo(o2.getId());
                    }
                });
        for (SysUser user : users) {
            List<SysRole> roles = roleService.findRolesByUserId(user.getId());
            map.put(user, roles);
        }

        //查询所有角色
        List<SysRole> roles = userService.findRoles();
        request.setAttribute("username", username);
        request.setAttribute("map", map);
        request.setAttribute("roles", roles);
        return "backend_page/manager-power";
    }

    @RequiresPermissions("power:updateAuthority")
    @RequestMapping(value = "/updateAuthority", name = "更新权限")
    public String updateAuthority(Model model,HttpServletRequest request) throws UnsupportedEncodingException, ClassNotFoundException {
        String username = "未登录";
        SysUser currentLoginUser = RequestUtils.currentLoginUser();

        if (currentLoginUser != null && StringUtils.isNotEmpty(currentLoginUser.getUserName())) {
            username = currentLoginUser.getUserName();
        } else {
            return "redirect:/adminLogin/toLogin";
        }
        //获取本类的对象
        Class clas = PowerController.class;
        //获取包路径
        String packageName = clas.getPackage().getName().replaceAll("\\.","/");
        //获取类所在的绝对根路径
        String path = clas.getResource("/").getPath();
        path = URLDecoder.decode(path, "UTF-8");
        String filePath = path + packageName;
        //找到该类下的所有类文件
        File file = new File(filePath);
        File[] files = file.listFiles();

        List<SysResources> resources = new ArrayList<>();
        for (File file1 : files) {
            if (file1.isDirectory()){
                continue;
            }else {
                //获取类名
                String className = file1.getName().substring(0, file1.getName().lastIndexOf(".class"));
                //去掉内部类的情况
                if (className.indexOf("$") != -1) {
                    //去掉内部类
                    //className = className.substring(0, className.indexOf("$"));
                    continue;
                }

                //获取类的反射
                Class clas2 = Class.forName(clas.getPackage().getName()+"."+className);
                //获取每个类的RequestMapping注解
                RequestMapping requestMapping = (RequestMapping) clas2.getAnnotation(RequestMapping.class);
                //设置得到的跟目录
                SysResources sr1 = new SysResources();
                sr1.setUserName(requestMapping.name());
                String controllerUrl = requestMapping.value()[0];
                //判断是不是以/开头
                controllerUrl = controllerUrl.startsWith("/")?controllerUrl:"/"+controllerUrl;
                sr1.setResUrl(controllerUrl);
                /*resources.add(sr1);*/
                //获取所有方法的请求
                Method[] methods = clas2.getDeclaredMethods();
                for (Method method : methods) {
                    RequestMapping requestMapping2 = method.getAnnotation(RequestMapping.class);
                    if (requestMapping2 != null) {
                        SysResources sr2 = new SysResources();
                        sr2.setUserName(requestMapping2.name());
                        String methodUrl = requestMapping2.value()[0];
                        //判断是不是以/开头
                        methodUrl = methodUrl.startsWith("/")?methodUrl:"/"+methodUrl;
                        sr2.setResUrl(sr1.getResUrl()+methodUrl);
                        resources.add(sr2);
                    }
                }
            }

        }
        //数据库查询的所有资源权限数据
        List<SysResources> resourcesAll = userService.findPermissions();
        List<SysResources> resourcesAdd = new ArrayList<>();
        //查找没有增加进去的资源权限
        for (SysResources resource : resources) {
            boolean flag = false;
            //一个一个去比较
            for (SysResources sysResources : resourcesAll) {
                if (resource.getResUrl().equals(sysResources.getResUrl())) {
                    flag = true;//已存在，不加入
                    break;
                }
            }
            if (!flag) {
                //没有进入if条件，证明不存在
                resourcesAdd.add(resource);
            }
        }
        int count = resourcesService.addResources(resourcesAdd);
        request.setAttribute("username", username);
        resourcesAll = userService.findPermissions();
        model.addAttribute("resources", resourcesAll);
        model.addAttribute("count", count);
        return "backend_page/synchroAuthority";
    }


    @RequiresPermissions("power:queryAllAuthority")
    @RequestMapping(value = "/queryAllAuthority", name = "查询所有权限并分配")
    public String queryAllAuthority(Model model, SysRole sysRole) {
        String username = "未登录";
        SysUser currentLoginUser = RequestUtils.currentLoginUser();

        if (currentLoginUser != null && StringUtils.isNotEmpty(currentLoginUser.getUserName())) {
            username = currentLoginUser.getUserName();
        } else {
            return "redirect:/adminLogin/toLogin";
        }
        List<SysResources> resources = userService.findPermissions();
        //查询所有的角色
        List<SysRole> roles = userService.findRoles();
        //根据角色的id查询对应的权限
        List<SysResources> resourcesRoles = userService.findPermissionsByRoleId(sysRole.getId());
        //匹配每一个是否有权限
        Map<SysResources, Object> map = new TreeMap<SysResources, Object>(
                new Comparator<SysResources>() {
                    @Override
                    public int compare(SysResources o1, SysResources o2) {
                        return o1.getResUrl().compareTo(o2.getResUrl());
                    }
                });
        for (SysResources resource : resources) {
            boolean flag = false;
            for (SysResources resourcesRole : resourcesRoles) {
                if (resource.getResUrl().equals(resourcesRole.getResUrl())) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                map.put(resource, 1);
            } else {
                map.put(resource, 0);
            }
        }
        model.addAttribute("username", username);
        model.addAttribute("roles", roles);
        model.addAttribute("sysRole", sysRole);
        model.addAttribute("resourcesMap", map);
        return "backend_page/assignPermissions";
    }

    @RequiresPermissions("power:addAuthority")
    @RequestMapping(value = "/addAuthority", name = "增加角色权限")
    public String addAuthority(SysRoleResources roleResources, Integer has, String roleDesc){
        if (has == 1) {
            //需要增加权限
            roleService.addAuthority(roleResources);
        } else {
            //需要删除权限
            roleService.deleteAuthority(roleResources);
        }
        return "redirect:/power/queryAllAuthority?id="+roleResources.getRoleId()+"&roleDesc="+roleDesc;
    }


    @RequiresPermissions("power:lock")
    @RequestMapping(value = "/lock", name = "解锁和锁定角色")
    public String lock(Integer userId, Integer userEnable){
        boolean result = userService.updateUserByLock(userId, userEnable);
        return "redirect:/power/toPowerIndex";
    }

    @RequiresPermissions("power:giveRole")
    @RequestMapping(value = "/giveRole", name = "赋予用户角色")
    public String giveRole(SysUserRole userRole, boolean checked) {
        if (checked) {
            //为true代表被选中

            boolean result = userService.addUserRole(userRole);
        } else {
            //否则去除权限
            boolean result = userService.deleteUserRole(userRole);
        }

        return "redirect:/power/toPowerIndex";
    }

/*    @RequestMapping("/403")
    public String toForbiden(){
        return "/backend_page/403";
    }*/
}
